package com.hhq.sso.auth.base.api;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import com.hhq.sso.auth.base.util.SystemUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import com.hhq.sso.auth.base.entity.SystemUser;
import com.hhq.sso.auth.base.pojo.SystemUserInfo;
import com.hhq.sso.auth.base.util.JwtUtils;
import com.hhq.sso.common.api.CommonResult;
import com.hhq.sso.common.api.request.LoginRequest;

/**
 * <p>
 * Description: 登录接口
 * </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/20 10:53
 */
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public CommonResult<SystemUserInfo> login(@RequestBody LoginRequest request) {
        try {
            UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
            Authentication authentication = authenticationManager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            SystemUser systemUser = (SystemUser)authentication.getPrincipal();
            // 获取用户权限信息
            String authorityString = "";
            Collection<? extends GrantedAuthority> authorities = systemUser.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                authorityString = authority.getAuthority();
            }
            // 用户身份验证成功，生成并返回jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", systemUser.getUsername());
            claims.put("userId", systemUser.getId());
            claims.put("tenantId", systemUser.getTenantId());
            claims.put("authorityString", authorityString);
            String jwtToken = jwtUtils.getJwt(claims);

            SystemUserInfo systemUserInfo = BeanUtil.toBean(claims, SystemUserInfo.class);
            systemUserInfo.setToken(jwtToken);
            return CommonResult.data(systemUserInfo);
        } catch (Exception ex) {
            // 用户身份验证失败，返回登陆失败提示
            return CommonResult.fail("用户名或密码错误！");
        }

    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public CommonResult<SystemUserInfo> info() {
        return CommonResult.data(SystemUserContext.getSystemUserInfo());
    }

}
